package xin.yangshuai.springsecurity03.textmessage;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class TextMessageAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        if (!TextMessageAuthenticationToken.class.isInstance(authentication)) {
            return null;
        }

        String phone = authentication.getPrincipal().toString();
        String code = authentication.getCredentials().toString();

        // 验证验证码是否正确，这里演示固定验证码为：123456
        if (!"123456".equals(code)) {
            throw new InternalAuthenticationServiceException("验证码验证失败");
        }

        // 借用UserDetailsService，传入phone做为username
        UserDetails user = userDetailsService.loadUserByUsername(phone);
        if (user == null) {
            throw new InternalAuthenticationServiceException("用户未找到");
        }

        TextMessageAuthenticationToken result = TextMessageAuthenticationToken.authenticated(user, code, user.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return TextMessageAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    protected UserDetailsService getUserDetailsService() {
        return this.userDetailsService;
    }
}
